package hk.com.fgoproduction.getdroplets.Service

import android.app.Notification
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.util.Log
import com.dropbox.core.v2.files.FileMetadata
import hk.com.fgoproduction.getdroplets.DropboxAPI.AFile
import hk.com.fgoproduction.getdroplets.Lib.Common.ThisApplication
import hk.com.fgoproduction.getdroplets.R
import java.io.File
import java.util.*

class FileCompareService() : Service(), ThisApplication.BgThreadCallback {

    var obj: AFile? = null
    var path = ""
    private val ID = 0x1234

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()

        obj = (application as ThisApplication).fileApiFactory(this)
        startForeground(ID, getNotiBuilder(this).build())
    }

    private fun getNotiBuilder(context: Context, title: String = "Ver Checking", text: String = "Verifying rev") : Notification.Builder {
        return Notification.Builder(context)
                .setContentTitle(title)
                .setContentText(text)
                .setSmallIcon(R.drawable.notification_template_icon_bg)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val path = intent!!.getStringExtra("path")
        val localPath = intent.getStringExtra("localPath")

        (application as ThisApplication).runOnBgWithCb(Runnable {
            obj?.getFolderList(path)?.entries?.forEach {
                if (it is FileMetadata) {
                    val name = it.name
                    Log.d("name", name)
                    val file = File(localPath)
                    if (file.isDirectory) {
                        val localFile = file.listFiles().find { it.name == name }
                        val localModi = localFile?.lastModified()

                        if (localModi != null) {
                            Log.d("local", Date(localModi).toString())
                            Log.d("server", it.clientModified.toString())
                            val diff = localModi - it.clientModified.time
                            when {
                                diff == 0L -> Log.d("result", "identical")
                                diff < 0L -> Log.d("result", "server is newer")
                                diff > 0L -> Log.d("result", "local is newer")
                            }
                        }
                    }
                }
            }
        }, this)

        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    override fun threadFinish() {
        stopSelf()
    }
}